package com.learn.service.impl;

import com.learn.dao.AccountDao;
import com.learn.pojo.Account;
import com.learn.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/01/19
 * @description
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountDao accountDao;
    @Resource
    private AccountService accountService2;

    @Transactional
    @Override
    public void transfer(int fromId, int toId, double money) {
        Account from = accountDao.selectById(fromId);
        Account to = accountDao.selectById(toId);
        if (from.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        from.setBalance(from.getBalance() - money);
        to.setBalance(to.getBalance() + money);

        int count = accountDao.updateBalance(from);
//        String s = null;
//        s.toString();
        count += accountDao.updateBalance(to);
        if (count != 2) {
            throw new RuntimeException("系统异常");
        }
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void insert(Account account) {
        accountDao.insert(account);
        Account account1= new Account(account.getId()+1, 2300.0);
        try {
            accountService2.insert(account1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
